<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brandIndex\BrandQuestionCategory;
use Biz\model\brandIndex\BrandQuestions;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class BrandQuestionsController extends Controller
{
    const PAGE_SIZE = 20;
    const DEFAULT_HAOHAOZHU_UID = 11941;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function questionList(Request $request, Content $content, $step = 1)
    {
        //动态获取tab
        $tab = new Tab();
        $stages = BrandQuestionCategory::getCategorys();
        $types_arr = [];
        if ($stages && is_array($stages)) {
            foreach ($stages as $stage) {
                $types_arr[$stage['id']] = $stage['category_name'];
                $tab->addLink($stage['category_name'], '/admin/brand/questionlist/' . $stage['id'] . '/index', $step == $stage['id']);
            }
        }
        //问答列表
        $question_list = (array)BrandQuestions::getQuestions($step);
        $count = (int)count($question_list);

        $gridModel = new pGridDataModel($question_list, $count, []);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();

            $grid->tools(function ($tools) {
                $tools->append("<a href='/admin/brand/grouplist/index' class='btn btn-sm btn-success' style='float: right;'><i class='fa fa-bars'>&nbsp;&nbsp;问答分组管理</i></a>");
            });

            $grid->column('id', 'id')->sort()->width(100);
            $grid->column('question_content', '问题')->width(200);
            $grid->column('pic_id', '回答解释图片')->display(function () {
                return "<img src='" . ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->pic_id, ImgUrl::IMAGE_SIZE_OP_ORI) . "' width=300 /><br>添加时间：" . $this->addtime . "<br>最后修改时间：" . $this->edittime;
            })->width(350);
            $grid->column('answer_content', '回答内容')->width(400);
        });

        return $content
            ->header('问答管理')
            ->body($tab)->row($listGrid);

    }

    //添加问答
    public function addQuestion(Request $request, Content $content, $step)
    {
        $request = $request->all();
        return $content
            ->header('添加问答')
            ->breadcrumb(
                ['text' => '问答管理', 'url' => '/brand/questionlist/' . $step . '/index'],
                ['text' => '添加问答', 'url' => '/brand/questionlist/' . $step . '/index/create']
            )
            ->body(self::editAction($request, $id = 0, $step));

    }

    //修改
    public function editQuestion(Request $request, Content $content, $step, $id)
    {

        $request = $request->all();
        return $content
            ->header('修改问答')
            ->breadcrumb(
                ['text' => '问答列表', 'url' => '/brand/questionlist/' . $step],
                ['text' => '修改问答', 'url' => '/brand/questionlist/' . $step . '/' . $id . '/edit']
            )
            ->body(self::editAction($request, $id, $step));


    }

    public function editAction($request, $id = 0, $step)
    {
        $stages = BrandQuestionCategory::getCategorys();
        $types_arr = [];
        if ($stages && is_array($stages)) {
            foreach ($stages as $stage) {
                $types_arr[$stage['id']] = $stage['category_name'];
            }
        }
        $data = [];
        if ($id != 0) {
            //修改
            $data = BrandQuestions::getQuestionsById($id);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            //添加
            $form = new Form($data);
        }
        $form->textarea('question_content', '问题')->required('不能为空');
        $form->select('category_type', '问题分组')->options($types_arr)->required('不能为空');
        $form->textarea('answer_content', '回答答案');
        $form->imgUpload('pic_id', '回答配图', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->number('question_sort', '问题排序')->help('问题排序，会按照由小到大的顺序在前端展示')->default(0);
        $form->action('/admin/brand/questionlist/' . $step . '/save');

        return $form->render();
    }

    //提交
    public function save(Request $request, Content $content, $step)
    {
        $request = $request->all();
        $rs = false;
        $data['question_content'] = $request['question_content'];
        $data['pic_id'] = $request['pic_id'];
        $data['question_sort'] = (int)$request['question_sort'];
        $data['category_type'] = (int)$request['category_type'];
        $data['answer_content'] = (string)$request['answer_content'];
        $data['question_status'] = BrandQuestions::STATUS_NORMAL;
        $data['admin_id'] = Admin::user()->id;

        if (isset($request['id']) && $request['id']) {
            $data['edittime'] = date('Y-m-d H:i:s', time());
            //修改
            $rs = BrandQuestions::editData($data, ['id' => $request['id']]);
        } else {
            //添加
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = BrandQuestions::addData($data);
        }

        if ($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/brand/questionlist/' . $step . '/index')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'
            ]);
            return redirect('/admin/brand/questionlist/' . $step . '/index')->with(compact('error'));
        }
    }

    //删除
    public function delQuestion($step, $id)
    {
        $data = BrandQuestions::getQuestionsById($id);
        if ($data) {
            $data['question_status'] = BrandQuestions::STATUS_DELETE;
            $data['edittime'] = date('Y-m-d H:i:s', time());

            $rs = BrandQuestions::editData($data, ['id' => $id]);
            if ($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    //拖动排序
    public function sort(Request $request, $step)
    {
        $request = $request->all();
        $sorts = $request['sort'];
        if ($sorts && is_array($sorts)) {
            foreach ($sorts as $id => $sort) {
                $data['question_sort'] = $sort;
                $data['edittime'] = date('Y-m-d H:i:s', time());
                BrandQuestions::editData($data, ['id' => $id]);
            }
        }
    }


    public function groupList(Request $request, Content $content, $step = 1)
    {
        //问答列表
        $category_list = (array)BrandQuestionCategory::getCategorys();
        $count = (int)count($category_list);

        $gridModel = new pGridDataModel($category_list, $count, []);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();

            $grid->column('id', 'id')->sort();
            $grid->column('category_name', '问题分组名');
        });

        return $content
            ->header('问答分组管理')
            ->breadcrumb(
                ['text' => '问答管理', 'url' => '/brand/questionlist/1/index'],
                ['text' => '问答分组', 'url' => '/brand/grouplist/index']
            )
            ->body($listGrid);

    }

    //添加问答分组
    public function addQuestionCategory(Request $request, Content $content)
    {
        $request = $request->all();
        return $content
            ->header('添加问答分组')
            ->breadcrumb(
                ['text' => '问答分组管理', 'url' => '/brand/grouplist/inex'],
                ['text' => '添加问答分组', 'url' => '/brand/grouplist/index/create']
            )
            ->body(self::editCategoryAction($request, $id = 0));

    }

    //修改分组名
    public function editQuestionCategory(Request $request, Content $content, $id)
    {

        $request = $request->all();
        return $content
            ->header('修改问答分组')
            ->breadcrumb(
                ['text' => '问答分组列表', 'url' => '/brand/grouplist/index/'],
                ['text' => '修改问答分组', 'url' => '/brand/grouplist/index/' . $id . '/edit']
            )
            ->body(self::editCategoryAction($request, $id));


    }

    public function editCategoryAction($request, $id = 0)
    {
        $data = [];
        if ($id != 0) {
            //修改
            $data = BrandQuestionCategory::getById($id);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            //添加
            $form = new Form($data);
        }
        $form->text('category_name', '问题分组名')->required('不能为空');
        $form->number('category_sort', '问题分组排序')->help('问题分组排序，会按照由小到大的顺序在前端展示')->default(0);
        $form->action('/admin/brand/grouplist/save');

        return $form->render();
    }

    //提交
    public function saveCategory(Request $request, Content $content)
    {
        $request = $request->all();
        $rs = false;
        $data['category_name'] = $request['category_name'];
        $data['category_sort'] = (int)$request['category_sort'];
        $data['category_status'] = BrandQuestionCategory::STATUS_NORMAL;
        $data['admin_id'] = Admin::user()->id;

        if (isset($request['id']) && $request['id']) {
            $data['edittime'] = date('Y-m-d H:i:s', time());
            //修改
            $rs = BrandQuestionCategory::editData($data, ['id' => $request['id']]);
        } else {
            //添加
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = BrandQuestionCategory::addData($data);
        }

        if ($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/brand/grouplist/index')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'
            ]);
            return redirect('/admin/brand/grouplist/index')->with(compact('error'));
        }
    }

    //删除
    public function delQuestionCategory($id)
    {
        $data = BrandQuestionCategory::getById($id);
        if ($data) {
            $data['category_status'] = BrandQuestionCategory::STATUS_DELETE;
            $data['edittime'] = date('Y-m-d H:i:s', time());

            $rs = BrandQuestionCategory::editData($data, ['id' => $id]);
            if ($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sortCategory(Request $request)
    {
        $request = $request->all();
        $sorts = $request['sort'];
        if ($sorts && is_array($sorts)) {
            foreach ($sorts as $id => $sort) {
                $data['category_sort'] = $sort;
                $data['edittime'] = date('Y-m-d H:i:s', time());
                BrandQuestionCategory::editData($data, ['id' => $id]);
            }
        }
    }

}

